from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from flask import current_app
from werkzeug.security import generate_password_hash, check_password_hash

def get_user_model():
    from backend.models.user import User
    return User

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login', methods=['POST'])
def login():
    """用户登录"""
    try:
        current_app.logger.info('收到登录请求')
        
        if not request.is_json:
            return jsonify({'error': '请求格式错误，需要JSON格式'}), 400
            
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        
        current_app.logger.info(f'登录尝试: 用户名={username}')
        
        if not username or not password:
            return jsonify({'error': '用户名和密码不能为空'}), 400
        
        User = get_user_model()
        user = User.query.filter_by(username=username).first()
        
        if user and user.check_password(password):
            access_token = create_access_token(identity=user.id)
            current_app.logger.info(f'用户 {username} 登录成功')
            return jsonify({
                'access_token': access_token,
                'user': {
                    'id': user.id,
                    'username': user.username
                }
            }), 200
        else:
            current_app.logger.warning(f'用户 {username} 登录失败：用户名或密码错误')
            return jsonify({'error': '用户名或密码错误'}), 401
            
    except Exception as e:
        current_app.logger.error(f'登录异常: {str(e)}')
        return jsonify({'error': f'登录失败: {str(e)}'}), 500

@auth_bp.route('/profile', methods=['GET'])
@jwt_required()
def get_profile():
    """获取用户信息"""
    try:
        user_id = get_jwt_identity()
        User = get_user_model()
        user = User.query.get(user_id)
        
        if user:
            return jsonify({
                'id': user.id,
                'username': user.username,
                'created_at': user.created_at.isoformat() if user.created_at else None
            }), 200
        else:
            return jsonify({'error': '用户不存在'}), 404
            
    except Exception as e:
        return jsonify({'error': f'获取用户信息失败: {str(e)}'}), 500

@auth_bp.route('/init', methods=['POST'])
def init_admin():
    """初始化管理员账户"""
    try:
        User = get_user_model()
        # 检查是否已存在管理员账户
        admin = User.query.filter_by(username='admin').first()
        if admin:
            return jsonify({'message': '管理员账户已存在'}), 200
        
        # 创建管理员账户
        admin = User(username='admin')
        admin.set_password('admin123')
        
        # 使用正确的数据库实例
        from backend.app import db
        db.session.add(admin)
        db.session.commit()
        
        return jsonify({'message': '管理员账户创建成功'}), 201
        
    except Exception as e:
        current_app.logger.error(f'初始化管理员账户失败: {str(e)}')
        return jsonify({'error': f'初始化失败: {str(e)}'}), 500 